import 'package:app/router/router.dart';
import 'package:app/theme/design_tokens.dart';
import 'package:app/widgets/icons/close_icon.dart';
import 'package:app/widgets/message.dart';
import 'package:creato_ui/creato_ui.dart';
import 'package:flutter/material.dart';

// 手机号还是邮箱都来这个页面，写一个枚举
enum EditAccountPageActionType { phone, email }

class EditAccountPage extends StatefulWidget {
  const EditAccountPage({super.key, required this.actionType});

  final EditAccountPageActionType actionType; // 功能类型

  @override
  State<EditAccountPage> createState() => _EditPhonePageState();
}

class _EditPhonePageState extends State<EditAccountPage> {
  final TextEditingController _accountTextController = TextEditingController();

  // FocusNode用于监听输入框焦点变化
  FocusNode _focusNode = FocusNode();
  // GlobalKey用于获取AnimateDivider的实例
  final GlobalKey<_AnimateDividerState> _animateDividerKey = GlobalKey();

  @override
  void initState() {
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        _animateDividerKey.currentState?.start();
      } else {
        _animateDividerKey.currentState?.reset();
      }
    });
    super.initState();
  }

  // 根据类型写不同的校验方法
  bool _validate(EditAccountPageActionType actionType, String? text) {
    switch (actionType) {
      case EditAccountPageActionType.phone:
        if (text == null) {
          Message.showToast(msg: "请输入手机号");
          return false;
        }
        if (RegExp(r'^1[3-9]\d{9}$').hasMatch(text!) == false) {
          Message.showToast(msg: "请输入正确的手机号");

          return false;
        }
      case EditAccountPageActionType.email:
        if (text == null) {
          Message.showToast(msg: "请输入邮箱");
          return false;
        }
        if (RegExp(r'^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$')
                .hasMatch(text) ==
            false) {
          Message.showToast(msg: "请输入正确的邮箱");
          return false;
        }
    }
    // 校验通过
    return true;
  }

  // 输入框提示文字
  String get _hintText {
    switch (widget.actionType) {
      case EditAccountPageActionType.phone:
        return "请输入手机号";
      case EditAccountPageActionType.email:
        return "请输入邮箱";
    }
  }

  // 输入框内容边距
  EdgeInsetsGeometry? get _contentPadding {
    switch (widget.actionType) {
      case EditAccountPageActionType.phone:
        return null; // 使用默认边距
      case EditAccountPageActionType.email:
        return const EdgeInsets.only(left: 0);
    }
  }

  // 输入框键盘类型
  TextInputType get _keyboardType {
    switch (widget.actionType) {
      case EditAccountPageActionType.phone:
        return TextInputType.phone;
      case EditAccountPageActionType.email:
        return TextInputType.emailAddress;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            print("失去焦点");
            _focusNode.unfocus();
          },
          child: Padding(
            padding: const EdgeInsets.fromLTRB(20, 40, 20, 0),
            child: Column(
              children: [
                _buildTitle(),
                const SizedBox(
                  height: 52,
                ),
                _buildInput(),
                AnimateDivider(
                  key: _animateDividerKey,
                  width: MediaQuery.of(context).size.width,
                ),
                const SizedBox(height: 40),
                CreatoButton(
                  text: "下一步",
                  block: true,
                  onPressed: () {
                    EditAccountPageActionType actionType = widget.actionType;
                    String text = _accountTextController.text.trim();
                    bool isValid = _validate(actionType, text);
                    if (!isValid) {
                      return;
                    }
                    String _actionType =
                        actionType == EditAccountPageActionType.phone
                            ? "phone"
                            : "email";
                    // 校验通过，跳转到验证码页面
                    router.push(
                        "/home/user_info/verification_code/$_actionType/$text");
                  },
                )
              ],
            ),
          )),
    );
  }

  // 标题
  Widget _buildTitle() {
    Widget _title;

    switch (widget.actionType) {
      case EditAccountPageActionType.phone:
        _title = const Text("输入新手机号");
        break;
      case EditAccountPageActionType.email:
        _title = const Text("输入新邮箱");
        break;
    }

    return Align(
        alignment: Alignment.centerLeft,
        child: DefaultTextStyle(
            style: const TextStyle(
                fontSize: 24,
                color: Color(0xFF383838),
                fontWeight: FontWeight.w600),
            child: _title));
  }

  // 输入框
  Widget _buildInput() {
    // 输入框组成
    List<Widget> inputGroup = [];

    // phone前面加上+86
    if (EditAccountPageActionType.phone == widget.actionType) {
      inputGroup.insert(
          0,
          const Text(
            "+86",
          ));
    }

    // 输入框
    inputGroup.add(Expanded(
      child: TextField(
        controller: _accountTextController,
        focusNode: _focusNode,
        decoration: InputDecoration(
          hintText: _hintText,
          contentPadding: _contentPadding,
        ),
        keyboardType: _keyboardType,
      ),
    ));

    // 右侧关闭按钮
    inputGroup.add(InkWell(
      splashColor: Colors.transparent,
      highlightColor: Colors.transparent,
      child: const Padding(
        padding: EdgeInsets.fromLTRB(10, 20, 0, 20),
        child: CloseIconWidget(),
      ),
      onTap: () {
        _accountTextController.clear();
      },
    ));

    return Row(
      children: inputGroup,
    );
  }
}

// 自定义的分割线控件
class AnimateDivider extends StatefulWidget {
  const AnimateDivider({
    super.key,
    required this.width,
    this.height = 1,
    this.backgroundColor = Colors.grey,
    this.activeColor,
    this.duration = const Duration(milliseconds: 500),
  });
  final double width;
  final double height;
  final Color backgroundColor;
  final Color? activeColor;
  final Duration duration;

  @override
  State<AnimateDivider> createState() => _AnimateDividerState();
}

class _AnimateDividerState extends State<AnimateDivider>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double?> _animation;

  Color get _activeColor => widget.activeColor ?? DesignTokens.primaryColor;
  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: widget.duration,
    );
    _animation =
        Tween<double?>(begin: 0, end: widget.width).animate(_controller);
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return Stack(
          children: [
            DecoratedBox(
              decoration: BoxDecoration(color: widget.backgroundColor),
              child: SizedBox(width: widget.width, height: widget.height),
            ),
            DecoratedBox(
              decoration: BoxDecoration(color: _activeColor),
              child: SizedBox(
                width: _animation.value,
                height: widget.height,
              ),
            )
          ],
        );
      },
    );
  }

  start() {
    _controller.forward();
  }

  reset() {
    _controller.reset();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}
